/****
 * 工具函数统一出口
 ****/
import dayjs from 'dayjs'
import Cookie from 'js-cookie'
import { isObject, get } from 'lodash-es'
import { Message } from 'element-ui'

export const DATE_FORMAT = 'YYYY-MM-DD'
export const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
export const DATE_MINUTE_FORMAT = 'YYYY-MM-DD HH:mm'
export const DEFAULT_RANGE_TIME = ['00:00:00', '23:59:59']

/**
 * 添加cookie
 * @param {string} name<必须>  // cookie名
 * @param {string} value<必须>  // cookie值
 * @param {number} expiresHours<必须>  // 过期时间
 **/
export const addCookie = (name, value, expiresHours) => {
  let cookieString = name + '=' + escape(value) + '; path=/'
  // 判断是否设置过期时间
  if (expiresHours > 0) {
    const date = new Date()
    date.setTime(date.getTime + expiresHours * 3600 * 1000)
    cookieString = cookieString + '; expires=' + date.toUTCString()
  }
  document.cookie = cookieString
}

/**
 * 获取cookie
 * @param {string} name<必须>  // cookie名
 **/
export const getCookie = name => {
  return Cookie.get(name)
}

/**
 * 删除cookie
 * @param {string} name<必须>  // cookie名
 **/
export const deleteCookie = name => {
  const date = new Date()
  date.setTime(date.getTime() - 10000)
  document.cookie = name + '=; path=/; expires=' + date.toUTCString()
}

/**
 * 获取url地址上的参数
 */
export const getUrlParams = () => {
  const paramStr = window.location.href.split('?')[1]
  const res = {}
  if (paramStr) {
    paramStr.split('&').forEach(item => {
      const itemInfo = item.split('=')
      const key = String(itemInfo[0])
      const value = String(itemInfo[1])
      if (key && (value || value === '')) {
        res[key] = value
      }
    })
  }
  return res
}

/**
 * 格式化日期
 * @param date 时间戳
 */
export const formatDate = date => date && dayjs(date).format(DATE_FORMAT)

/**
 * 格式化时间
 * @param time 时间戳
 */
export const formatDateTime = time => {
  return time && dayjs(time).format(DATE_TIME_FORMAT)
}

export const checkMobile = val => {
  // 校验手机号的正则
  const phoneReg = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
  return phoneReg.test(val)
}

export const routeBaseUrl = process.env.NODE_ENV === 'production' ? '/' : '/'

export function catchError(error, msg) {
  let errorMsg = '服务器异常'

  if (isObject(error)) {
    const errInfo = get(error, 'message', '服务器异常')
    errInfo && (errorMsg = errInfo)
  }

  if (msg) {
    errorMsg = msg
  }

  Message.error(errorMsg)
}

/**
 * 处理使用axios导出的返回数据
 * @param data 返回的Blob类型的数据
 * @param contentDisposition 相应头中content-disposition
 */
export const handleExportResponse = (data, fileName) => {
  const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })

  const downloadElement = document.createElement('a') // 创建a标签
  const href = window.URL.createObjectURL(blob) // 创建下载的链接
  downloadElement.href = href // 给元素设置href属性
  downloadElement.download = fileName // 下载后文件名
  document.body.appendChild(downloadElement) // 将元素加入页面
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}

/**
 *对比对象数组（对象属性里面还有数组）比较不同
 **/
export const compareObjectArrays = (arr1, arr2) => {
  if (arr1.length !== arr2.length) {
    return false
  }
  for (let i = 0; i < arr1.length; i++) {
    if (!compareObjects(arr1[i], arr2[i])) {
      return false
    }
  }
  return true
}

const compareObjects = (obj1, obj2) => {
  // 比较基本属性
  for (const key in obj1) {
    if (typeof obj1[key] === 'object' && obj1[key] !== null && typeof obj2[key] === 'object' && obj2[key] !== null) {
      // 如果属性是数组，则逐一比较数组元素
      if (!compareArrays(obj1[key], obj2[key])) {
        return false
      }
    } else if (obj1[key] !== obj2[key]) {
      return false
    }
  }
  return true
}

function compareArrays(arr1, arr2) {
  if (arr1.length !== arr2.length) {
    return false
  }
  for (let i = 0; i < arr1.length; i++) {
    if (typeof arr1[i] === 'object' && arr1[i] !== null && typeof arr2[i] === 'object' && arr2[i] !== null) {
      if (!compareObjects(arr1[i], arr2[i])) {
        return false
      }
    } else if (arr1[i] !== arr2[i]) {
      return false
    }
  }
  return true
}

// 判断权限点
export function permissionController(code) {
  const permissionList = JSON.parse(localStorage.getItem('user-permissions'))

  return permissionList.includes(code)
}
